from tkinter import *
import tkinter.messagebox
from tkinter import ttk
from tkinter import font
from src.backend.appointment_b import AppointmentBackend

class AppointmentFrontend:
    """Frontend UI for appointment management"""
    
    def __init__(self, master, user_type='admin'):
        self.master = master
        self.user_type = user_type
        self.backend = AppointmentBackend()
        
        self.master.title("HOSPITAL MANAGEMENT SYSTEM")
        self.master.geometry("1500x700+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()

        #=============ATTRIBUTES===========
        self.pat_ID = IntVar()
        self.staff_ID = StringVar()
        self.ap_date = StringVar()
        self.ap_time = StringVar()
        self.duration = IntVar()
        self.notes = StringVar()

        self.create_ui()

    def create_ui(self):
        """Create the user interface"""
        #===============TITLE==========
        self.lblTitle = Label(self.frame, text="APPOINTMENT FORM", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=50)
        
        #==============FRAME==========
        self.LoginFrame = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame.grid(row=1, column=0)
        
        self.LoginFrame2 = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame2.grid(row=2, column=0)
        
        self.create_form_fields()
        self.create_buttons()

    def create_form_fields(self):
        """Create form input fields"""
        #===========LABELS=============          
        self.lblpid = Label(self.LoginFrame, text="PATIENT ID", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblpid.grid(row=0, column=0)
        self.lblpid = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.pat_ID)
        self.lblpid.grid(row=0, column=1)
        
        self.lblstaff = Label(self.LoginFrame, text="STAFF ID", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblstaff.grid(row=1, column=0)
        self.lblstaff = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.staff_ID)
        self.lblstaff.grid(row=1, column=1)
        
        self.lbldate = Label(self.LoginFrame, text="APPOINTMENT DATE (YYYY-MM-DD)", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lbldate.grid(row=2, column=0)
        self.lbldate = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.ap_date)
        self.lbldate.grid(row=2, column=1)
        
        self.lbltime = Label(self.LoginFrame, text="APPOINTMENT TIME (HH:MM)", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lbltime.grid(row=3, column=0)
        self.lbltime = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.ap_time)
        self.lbltime.grid(row=3, column=1)
        
        self.lblduration = Label(self.LoginFrame, text="DURATION (minutes)", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblduration.grid(row=0, column=2)
        self.lblduration = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.duration)
        self.lblduration.grid(row=0, column=3)
        
        self.lblnotes = Label(self.LoginFrame, text="NOTES", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblnotes.grid(row=1, column=2)
        self.lblnotes = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.notes)
        self.lblnotes.grid(row=1, column=3)

    def create_buttons(self):
        """Create action buttons"""
        #===========BUTTONS============= 
        self.button2 = Button(self.LoginFrame2, text="BOOK APPOINTMENT", width=15, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.BOOK_APPOINTMENT)
        self.button2.grid(row=3, column=1, padx=5, pady=5)
        
        self.button3 = Button(self.LoginFrame2, text="UPDATE", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.UPDATE_APPOINTMENT)
        self.button3.grid(row=3, column=2, padx=5, pady=5)
        
        self.button4 = Button(self.LoginFrame2, text="DELETE", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.D_DISPLAY)
        self.button4.grid(row=3, column=3, padx=5, pady=5)
        
        self.button5 = Button(self.LoginFrame2, text="SEARCH", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.S_DISPLAY)
        self.button5.grid(row=3, column=4, padx=5, pady=5)
        
        self.button6 = Button(self.LoginFrame2, text="EXIT", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.Exit)
        self.button6.grid(row=3, column=5, padx=5, pady=5)
        
        # Add Global Search button only for root users
        if self.user_type == 'root':
            self.button7 = Button(self.LoginFrame2, text="GLOBAL SEARCH", width=15, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.GLOBAL_SEARCH)
            self.button7.grid(row=4, column=1, columnspan=2, pady=10)

    #FUNCTION TO BOOK APPOINTMENT
    def BOOK_APPOINTMENT(self):
        try:
            # Get form data
            appointment_data = {
                'patient_id': self.pat_ID.get(),
                'staff_id': self.staff_ID.get().strip(),
                'appointment_date': self.ap_date.get().strip(),
                'appointment_time': self.ap_time.get().strip(),
                'duration': self.duration.get(),
                'notes': self.notes.get().strip()
            }
            
            # Validate data
            is_valid, message = self.backend.validate_appointment_data(appointment_data)
            if not is_valid:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", message)
                return
            
            # Add appointment to database
            appointment_id = self.backend.add_appointment(appointment_data)
            
            if appointment_id:
                tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", f"Appointment booked successfully with ID: {appointment_id}")
                self.clear_form()
            else:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to book appointment")
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")
    
    def clear_form(self):
        """Clear all form fields"""
        self.pat_ID.set(0)
        self.staff_ID.set("")
        self.ap_date.set("")
        self.ap_time.set("")
        self.duration.set(30)
        self.notes.set("")
        
    #FUNCTION TO UPDATE APPOINTMENT
    def UPDATE_APPOINTMENT(self):
        try:
            appointment_id = self.pat_ID.get()
            if not appointment_id or appointment_id <= 0:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Please enter a valid Appointment ID to update")
                return
            
            # Check if appointment exists
            appointment = self.backend.get_appointment(appointment_id)
            if not appointment:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Appointment not found")
                return
            
            # Get form data - allow partial updates
            update_data = {}
            if self.staff_ID.get().strip():
                update_data['staff_id'] = self.staff_ID.get().strip()
            if self.ap_date.get().strip():
                update_data['appointment_date'] = self.ap_date.get().strip()
            if self.ap_time.get().strip():
                update_data['appointment_time'] = self.ap_time.get().strip()
            
            # Allow duration update even if 0 (relaxed restriction)
            duration = self.duration.get()
            if duration > 0:  # Only include if explicitly set to positive value
                update_data['duration'] = duration
            
            # Notes can be empty or updated
            notes = self.notes.get().strip()
            if notes or notes == "":  # Allow clearing notes
                update_data['notes'] = notes
            
            if not update_data:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "No data to update")
                return
            
            # Update appointment
            if self.backend.update_appointment(appointment_id, update_data):
                tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Appointment updated successfully")
                self.clear_form()
            else:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to update appointment")
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")
            
    #FUNCTION TO EXIT APPOINTMENT WINDOW
    def Exit(self):            
        self.master.destroy()

    #FUNCTION TO OPEN DELETE APPOINTMENT DISPLAY WINDOW
    def D_DISPLAY(self):
        self.newWindow = Toplevel(self.master)
        self.app = DMenu(self.newWindow, self.backend)
        
    #FUNCTION TO OPEN SEARCH APPOINTMENT DISPLAY WINDOW
    def S_DISPLAY(self):
        self.newWindow = Toplevel(self.master)
        self.app = SMenu(self.newWindow, self.backend)
    
    #FUNCTION TO OPEN GLOBAL SEARCH WINDOW (ROOT ONLY)
    def GLOBAL_SEARCH(self):
        self.newWindow = Toplevel(self.master)
        self.app = GlobalSearchMenu(self.newWindow, self.backend)

#CLASS FOR DISPLAY MENU FOR DELETE APPOINTMENT
class DMenu:
    def __init__(self, master, backend):    
        self.master = master
        self.backend = backend
        self.master.title("HOSPITAL MANAGEMENT SYSTEM")
        self.master.geometry("1500x700+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()
        self.del_aid = IntVar()
        self.lblTitle = Label(self.frame, text="DELETE APPOINTMENT WINDOW", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=50)
        #==============FRAME==========
        self.LoginFrame = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame.grid(row=1, column=0)
        self.LoginFrame2 = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame2.grid(row=2, column=0)
        #===========LABELS=============          
        self.lblaid = Label(self.LoginFrame, text="ENTER APPOINTMENT ID TO DELETE", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblaid.grid(row=0, column=0)
        self.lblaid = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.del_aid)
        self.lblaid.grid(row=0, column=1)

        self.DeleteB = Button(self.LoginFrame2, text="DELETE", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.DELETE_APPOINTMENT)
        self.DeleteB.grid(row=3, column=1, padx=5, pady=5)

    #FUNCTION TO DELETE APPOINTMENT
    def DELETE_APPOINTMENT(self):        
        try:
            appointment_id = self.del_aid.get()
            if not appointment_id:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Please enter Appointment ID to delete")
                return
            
            # Check if appointment exists
            appointment = self.backend.get_appointment(appointment_id)
            if not appointment:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Appointment record not found")
                return
            
            # Confirm deletion
            result = tkinter.messagebox.askyesno("HOSPITAL DATABASE SYSTEM", 
                                               f"Are you sure you want to delete appointment {appointment_id}?")
            if result:
                if self.backend.delete_appointment(appointment_id):
                    tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Appointment deleted successfully")
                    self.del_aid.set(0)
                else:
                    tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to delete appointment")
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")

#CLASS FOR SEARCH MENU FOR SEARCH APPOINTMENT
class SMenu:
    def __init__(self, master, backend):    
        self.master = master
        self.backend = backend
        self.master.title("HOSPITAL MANAGEMENT SYSTEM")
        self.master.geometry("1500x700+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()
        self.s_aid = StringVar()
        self.lblTitle = Label(self.frame, text="SEARCH APPOINTMENT WINDOW", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=25)
        #==============FRAME==========
        self.LoginFrame = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame.grid(row=1, column=0)
        self.LoginFrame2 = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame2.grid(row=2, column=0)
        
        #===========LABELS=============          
        self.lblaid = Label(self.LoginFrame, text="ENTER APPOINTMENT ID TO SEARCH", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblaid.grid(row=0, column=0)
        self.lblaid = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.s_aid)
        self.lblaid.grid(row=0, column=1)

        self.SearchB = Button(self.LoginFrame2, text="SEARCH", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.SEARCH_APPOINTMENT)
        self.SearchB.grid(row=0, column=1, padx=5, pady=5)
        
    #FUNCTION TO SEARCH APPOINTMENT
    def SEARCH_APPOINTMENT(self):
        try:
            search_term = self.s_aid.get().strip()
            if not search_term:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Please enter Appointment ID to search")
                return
            
            # Clear previous search results
            self.clear_search_results()
            
            # Try to search by ID
            appointment = None
            if search_term.isdigit():
                appointment = self.backend.get_appointment(int(search_term))
            
            if appointment:
                self.display_appointment_info(appointment)
            else:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "APPOINTMENT RECORD NOT FOUND")
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")
    
    def clear_search_results(self):
        """Clear previous search result labels"""
        for widget in self.LoginFrame.winfo_children():
            if isinstance(widget, Label) and widget.grid_info().get('row', 0) > 0:
                widget.destroy()
    
    def display_appointment_info(self, appointment):
        """Display appointment information"""
        # Appointment data structure: (appointment_id, patient_id, staff_id, appointment_date, appointment_time, duration, notes)
        
        self.l1 = Label(self.LoginFrame, text="APPOINTMENT ID", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l1.grid(row=1, column=0)
        self.dis1 = Label(self.LoginFrame, font="Arial 11 bold", bd=2, bg="#C0C0C0", text=str(appointment[0]))
        self.dis1.grid(row=1, column=1)
        
        self.l2 = Label(self.LoginFrame, text="PATIENT ID", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l2.grid(row=2, column=0)
        self.dis2 = Label(self.LoginFrame, font="Arial 11 bold", bd=2, bg="#C0C0C0", text=str(appointment[1]))
        self.dis2.grid(row=2, column=1)

        self.l3 = Label(self.LoginFrame, text="STAFF ID", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l3.grid(row=3, column=0)
        self.dis3 = Label(self.LoginFrame, font="Arial 11 bold", bg="#C0C0C0", bd=2, text=appointment[2])
        self.dis3.grid(row=3, column=1)

        self.l4 = Label(self.LoginFrame, text="APPOINTMENT DATE", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l4.grid(row=4, column=0)
        self.dis4 = Label(self.LoginFrame, font="Arial 11 bold", bg="#C0C0C0", bd=2, text=str(appointment[3]))
        self.dis4.grid(row=4, column=1)
        
        self.l5 = Label(self.LoginFrame, text="APPOINTMENT TIME", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l5.grid(row=5, column=0)
        self.dis5 = Label(self.LoginFrame, font="Arial 11 bold", bg="#C0C0C0", bd=2, text=str(appointment[4]))
        self.dis5.grid(row=5, column=1)
        
        self.l6 = Label(self.LoginFrame, text="DURATION", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l6.grid(row=1, column=2)
        self.dis6 = Label(self.LoginFrame, font="Arial 11 bold", bd=2, bg="#C0C0C0", text=str(appointment[5]) + " minutes")
        self.dis6.grid(row=1, column=3)
        
        self.l7 = Label(self.LoginFrame, text="NOTES", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l7.grid(row=2, column=2)
        self.dis7 = Label(self.LoginFrame, font="Arial 11 bold", bd=2, bg="#C0C0C0", text=appointment[6] or "N/A")
        self.dis7.grid(row=2, column=3)

#CLASS FOR GLOBAL SEARCH MENU (ROOT ONLY)
class GlobalSearchMenu:
    def __init__(self, master, backend):    
        self.master = master
        self.backend = backend
        self.master.title("GLOBAL SEARCH - ALL APPOINTMENTS")
        self.master.geometry("1200x600+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()
        
        self.lblTitle = Label(self.frame, text="GLOBAL APPOINTMENT SEARCH", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=25)
        
        # Create Treeview for displaying all appointments
        self.tree_frame = Frame(self.frame, bg="#C0C0C0")
        self.tree_frame.grid(row=1, column=0, padx=20, pady=10)
        
        # Define columns
        columns = ('ID', 'Patient ID', 'Staff ID', 'Date', 'Time', 'Duration', 'Notes')
        self.tree = ttk.Treeview(self.tree_frame, columns=columns, show='headings', height=15)
        
        # Define headings
        for col in columns:
            self.tree.heading(col, text=col)
            self.tree.column(col, width=120)
        
        # Add scrollbar
        scrollbar = ttk.Scrollbar(self.tree_frame, orient=VERTICAL, command=self.tree.yview)
        self.tree.configure(yscrollcommand=scrollbar.set)
        
        # Pack treeview and scrollbar
        self.tree.pack(side=LEFT, fill=BOTH, expand=True)
        scrollbar.pack(side=RIGHT, fill=Y)
        
        # Buttons frame
        self.button_frame = Frame(self.frame, bg="#C0C0C0")
        self.button_frame.grid(row=2, column=0, pady=10)
        
        self.refresh_btn = Button(self.button_frame, text="REFRESH", width=15, font="Arial 11 bold", 
                                bg="#C0C0C0", relief="raised", bd=2, command=self.refresh_data)
        self.refresh_btn.pack(side=LEFT, padx=5)
        
        self.edit_btn = Button(self.button_frame, text="EDIT SELECTED", width=15, font="Arial 11 bold", 
                              bg="#C0C0C0", relief="raised", bd=2, command=self.edit_selected)
        self.edit_btn.pack(side=LEFT, padx=5)
        
        self.delete_btn = Button(self.button_frame, text="DELETE SELECTED", width=15, font="Arial 11 bold", 
                                bg="#C0C0C0", relief="raised", bd=2, command=self.delete_selected)
        self.delete_btn.pack(side=LEFT, padx=5)
        
        self.close_btn = Button(self.button_frame, text="CLOSE", width=15, font="Arial 11 bold", 
                               bg="#C0C0C0", relief="raised", bd=2, command=self.close_window)
        self.close_btn.pack(side=LEFT, padx=5)
        
        # Load initial data
        self.refresh_data()
    
    def refresh_data(self):
        """Refresh the appointment data in the treeview"""
        try:
            # Clear existing data
            for item in self.tree.get_children():
                self.tree.delete(item)
            
            # Get all appointments from database
            appointments = self.backend.get_all_appointments()
            
            # Insert data into treeview
            for appointment in appointments:
                self.tree.insert('', 'end', values=(
                    appointment[0],  # ID
                    appointment[1],  # Patient ID
                    appointment[2],  # Staff ID
                    str(appointment[3]),  # Date
                    str(appointment[4]),  # Time
                    str(appointment[5]) + " min",  # Duration
                    appointment[6] or "N/A"  # Notes
                ))
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error loading data: {str(e)}")
    
    def edit_selected(self):
        """Edit the selected appointment"""
        selection = self.tree.selection()
        if not selection:
            tkinter.messagebox.showwarning("HOSPITAL DATABASE SYSTEM", "Please select an appointment to edit")
            return
        
        # Get selected appointment data
        item = self.tree.item(selection[0])
        appointment_id = item['values'][0]
        
        # Open edit window
        self.edit_window = Toplevel(self.master)
        self.edit_app = EditAppointmentWindow(self.edit_window, appointment_id, self.backend, self.refresh_data)
    
    def delete_selected(self):
        """Delete the selected appointment"""
        selection = self.tree.selection()
        if not selection:
            tkinter.messagebox.showwarning("HOSPITAL DATABASE SYSTEM", "Please select an appointment to delete")
            return
        
        # Get selected appointment data
        item = self.tree.item(selection[0])
        appointment_id = item['values'][0]
        patient_id = item['values'][1]
        
        # Confirm deletion
        result = tkinter.messagebox.askyesno("HOSPITAL DATABASE SYSTEM", 
                                           f"Are you sure you want to delete appointment {appointment_id} for patient {patient_id}?")
        if result:
            try:
                if self.backend.delete_appointment(appointment_id):
                    tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Appointment deleted successfully")
                    self.refresh_data()
                else:
                    tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to delete appointment")
            except Exception as e:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")
    
    def close_window(self):
        """Close the global search window"""
        self.master.destroy()

#CLASS FOR EDIT APPOINTMENT WINDOW
class EditAppointmentWindow:
    def __init__(self, master, appointment_id, backend, refresh_callback):
        self.master = master
        self.appointment_id = appointment_id
        self.backend = backend
        self.refresh_callback = refresh_callback
        
        self.master.title("EDIT APPOINTMENT")
        self.master.geometry("800x600+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()
        
        # Get appointment data
        self.appointment = self.backend.get_appointment(appointment_id)
        if not self.appointment:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Appointment not found")
            self.master.destroy()
            return
        
        # Create form variables
        self.pat_ID = IntVar(value=self.appointment[1])
        self.staff_ID = StringVar(value=self.appointment[2])
        self.ap_date = StringVar(value=str(self.appointment[3]))
        self.ap_time = StringVar(value=str(self.appointment[4]))
        self.duration = IntVar(value=self.appointment[5])
        self.notes = StringVar(value=self.appointment[6] or "")
        
        # Title
        self.lblTitle = Label(self.frame, text="EDIT APPOINTMENT", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=20)
        
        # Form frame
        self.form_frame = Frame(self.frame, bg="#C0C0C0")
        self.form_frame.grid(row=1, column=0, padx=20, pady=10)
        
        # Form fields
        row = 0
        Label(self.form_frame, text="APPOINTMENT ID:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Label(self.form_frame, text=appointment_id, font="Arial 11", bg="#C0C0C0").grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="PATIENT ID:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.pat_ID, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="STAFF ID:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.staff_ID, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="APPOINTMENT DATE (YYYY-MM-DD):", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.ap_date, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="APPOINTMENT TIME (HH:MM):", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.ap_time, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="DURATION (minutes):", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.duration, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="NOTES:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.notes, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        
        # Buttons
        self.button_frame = Frame(self.frame, bg="#C0C0C0")
        self.button_frame.grid(row=2, column=0, pady=20)
        
        Button(self.button_frame, text="SAVE", width=15, font="Arial 11 bold", 
               bg="#C0C0C0", relief="raised", bd=2, command=self.save_changes).pack(side=LEFT, padx=5)
        Button(self.button_frame, text="CANCEL", width=15, font="Arial 11 bold", 
               bg="#C0C0C0", relief="raised", bd=2, command=self.master.destroy).pack(side=LEFT, padx=5)
    
    def save_changes(self):
        """Save the changes to the appointment - relaxed restrictions"""
        try:
            # Validate required fields
            if not self.staff_ID.get().strip():
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Staff ID is required")
                return
            
            if not self.ap_date.get().strip():
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Appointment date is required")
                return
            
            if not self.ap_time.get().strip():
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Appointment time is required")
                return
            
            # Validate duration (allow 0 or positive)
            duration = self.duration.get()
            if duration < 0:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Duration cannot be negative")
                return
            
            update_data = {
                'patient_id': self.pat_ID.get(),
                'staff_id': self.staff_ID.get().strip(),
                'appointment_date': self.ap_date.get().strip(),
                'appointment_time': self.ap_time.get().strip(),
                'duration': duration,
                'notes': self.notes.get().strip()
            }
            
            if self.backend.update_appointment(self.appointment_id, update_data):
                tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Appointment updated successfully")
                self.refresh_callback()
                self.master.destroy()
            else:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to update appointment")
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")

